/**
 * Created by hejg on 2018/5/14.
 */
import React, {Component} from 'react';
import {
    View,
    Text,
    StyleSheet,
    TouchableHighlight,
    Alert,
    TouchableOpacity
} from 'react-native';
import {withNavigation} from 'react-navigation';
import Swiper from 'react-native-swiper';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import HomeModuleFrame from './HomeModuleFrame';
import Style from '../../../../components/Style';
import Tool from '../../../../components/Tool';
import Indicator from '../../../../components/Indicator';
import ChoseIcon from 'react-native-vector-icons/FontAwesome';
import ArrIcon from 'react-native-vector-icons/Foundation';

import Echarts from 'native-echarts';
const Color = Style.color;
var Dimensions = require('Dimensions');
export default withNavigation(class HomeOperateIndex extends Component {
    constructor(props) {
        super(props);
        this.state = {
            homeIndexItems: [],//指标数据集
            indicator: {visible: true, message: ''}//控制遮罩层
        };
    }

    componentDidMount() {
        let _this = this;
        Tool.fetchJson(Tool.appPath.mkst + 'homePageIndex/topIndex', JSON.stringify({
            pageNum: 1,
            pageSize: 15
        }), function (data) {
            if (data.state) {
                _this._handelDataItems(data.info.list);
                _this.setState({indicator: {visible: false, message: ''}});
            } else {
                _this.setState({indicator: {visible: true, message: data.info}});
            }
        }, function (error) {
            _this.setState({indicator: {visible: true, message: error}});
        }, function () {

        });
    }

    _handelDataItems(items) {
        let pageNum = 3;//每个Swiper显示的指标条数
        let homeIndexItems = new Array(Math.ceil(items.length / pageNum));
        for (let i = 0; i < items.length; i++) {
            if (i % pageNum == 0) {
                homeIndexItems[Math.floor(i / pageNum)] = new Array(pageNum);
            }
            homeIndexItems[Math.floor(i / pageNum)][(i % pageNum)] = {
                title: items[i].indexName,
                value: items[i].indexValue,
                ratio: items[i].specificValue,
                code: items[i].indexCode,
                type: items[i].fieldType
            };
        }
        this.setState({homeIndexItems: homeIndexItems});
    }

    render() {
        return (
            <View>
                <View style={{borderTopWidth:0,}}>
                        {this.state.homeIndexItems && this.state.homeIndexItems.map((sitem, sindex) => (
                            <View key={`HomeIndexSwiper_${sindex}`}>
                                {sitem && sitem.map((item, index) => (
                                    <HomeIndexItem title={item.title} value={item.value} ratio={item.ratio}
                                                   code={item.code} type={item.type}
                                                   key={`HomeIndexSwiperItem_${index}`}/>
                                ))}
                            </View>
                        ))}
                    <Indicator isVisible={this.state.indicator.visible} message={this.state.indicator.message}/>
                    {
                        this.state.indicator.visible || (this.state.homeIndexItems && this.state.homeIndexItems.length > 0) ?
                            null : <Indicator isVisible={true} message={Style.tip.noData} type="none"/>
                    }
                </View>
            </View>
        );
    }
})

const HomeIndexItem = withNavigation(class HomeIndexItem extends Component {

    _handleIndexValue(value, type) {
        let result = '-';
        switch (type) {
            case 1://整数
                result = Tool.numberFormat(this.props.value, 0);
                break;
            case 2://浮点数
                result = Tool.numberFormat(this.props.value, 2);
                break;
            case 3://百分比
                result = Tool.numberFormat(this.props.value * 100, 2) + '%';
                break;
        }
        return result;
    }
    constructor(props){
        super(props);
        this.state={
            isVisible:false,
        }
    }
    _showMap(){
        if(this.state.isVisible){
            this.setState({
                isVisible:false
            });
        }else{
            this.setState({
                isVisible:true
            });
        }
    }
    render() {
        const option = {
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top:'10%',
                containLabel: true
            },
            tooltip: {
                show: true,
                trigger: 'axis',
                formatter: '{c}',
                backgroundColor: 'rgba(0,0,0,0)',
                textStyle: {color: Color.blue},
                position: function (point, params, dom, rect, size) {
                    return [point[0], 5];
                },
                axisPointer: {type: 'line', lineStyle: {color:'#c0c0c0'}}
            },
            xAxis: {
                type: 'category',
                axisLabel: {textStyle: {color: Color.gray}},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false},
                data: [100, 200, 300]
            },
            yAxis: {
                type: 'value',
                axisLabel: {textStyle: {color:Color.gray}},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false}
            },
            series: [{
                type: 'line',
                smooth: true,
                data: [10,20,30]
            }],
            color: [Color.blue]
        }
        return (
            <View underlayColor={Style.color.lightGray} style={styles.touchableIndexItem}>
                <View style={styles.indexItemView}>
                    <TouchableOpacity
                        onPress={() => this.props.navigation.navigate('OperateIndex',{headerTitle:this.props.title,indexCode:this.props.code})}
                        style={{flex:1,paddingVertical:5, justifyContent:'space-between'}}>
                        <Text numberOfLines={1} style={styles.indexItemTitle}>{this.props.title}</Text>
                        <Text numberOfLines={1} style={styles.indexItemValue}>到达值：<Text style={{color:Style.color.blue,fontSize:Style.fontSize.middle}}>{this._handleIndexValue(this.props.value, this.props.type)}</Text></Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.indexItemRight}  onPress={()=>this._showMap()}>
                        <View style={{flexDirection:'column',marginRight:10}}>
                            <Text style={{textAlign:'right'}}>同比增幅</Text>
                            <View style={{flexDirection:'row'}}>
                                <ArrIcon name={'arrow-down'} size={20} color={'#af1c28'} style={{paddingRight:20}}/>
                                <Text numberOfLines={1} style={{color:'#af1c28',fontSize:Style.fontSize.normal}}>
                                {Tool.numberFormat(Math.abs(this.props.ratio * 100), 2)}%
                            </Text>
                            </View>
                        </View>
                        <View>
                            <ChoseIcon name={'angle-down'} size={20} color={Style.color.gray}/>
                        </View>
                    </TouchableOpacity>
                </View>
                {
                    this.state.isVisible == true ?
                        <View >
                            <View style={{
                                height:30,
                                shadowColor:Color.gray,
                                elevation: 1,
                                borderTopWidth:1,
                                borderColor:Color.lightGray,
                                borderBottomWidth:1,
                                backgroundColor:Color.white,
                                justifyContent:'center'
                            }}>
                                <Text style={{textAlign:'center',color:Color.black}}>近一年指标趋势变化</Text>
                            </View>
                            <View style={{
                                backgroundColor:Color.white,marginRight:8,marginLeft:8,
                                borderLeftWidth:1,
                                borderRightWidth:1,
                                borderStyle:'dotted',
                                borderColor:Color.lightGray,
                            }}>
                                <Echarts option={option} height={180} width={Dimensions.get('window').width}/>
                            </View>
                        </View>:null
                }
            </View>
        );
    }
})

const styles = StyleSheet.create({
    touchableIndexItem: {
        borderColor: Style.color.lightGray, borderBottomWidth: 1, marginBottom:5,
    },
    indexItemView: {
        flexDirection: 'row',
        backgroundColor:Style.color.white,
        height:60,
        paddingLeft:20,
        paddingRight:20,

    },
    indexItemCircle: {
        width: 10, height: 10, borderRadius: 5
    },
    indexItemLeft: {
        width: 40, alignItems: 'center', justifyContent: 'center', height: 50,
    },
    indexItemRight: {
        flexDirection: 'row',
        justifyContent: 'space-between', marginVertical: 5,
        alignItems:'center',
    },

    indexItemTitle: {
        fontWeight: 'bold', color: Style.color.black, fontSize: Style.fontSize.normal
    },
    indexItemValue: {
        fontSize: Style.fontSize.middle,
    }
});